package com.tian.view.draw.advance

import android.content.Context
import android.graphics.Canvas
import android.graphics.Color
import android.graphics.Paint
import android.util.AttributeSet
import android.view.View
import com.tian.util.view.DisplayUtil

/**
 * @author tiansongtao
 * @date 2023/1/4 15:29
 *
 * 绘制文字与图形阴影
 */
class ShadowLayerView(context: Context, attrs: AttributeSet?, defStyleAttr: Int) :
        View(context, attrs, defStyleAttr) {

    constructor(context: Context, attrs: AttributeSet?) : this(context, attrs, 0)
    constructor(context: Context) : this(context, null)

    init {
        setLayerType(LAYER_TYPE_SOFTWARE, null)
    }

    val paint = Paint().apply {
        color = Color.RED
        strokeWidth = DisplayUtil.dpToPx(2f)
        style = Paint.Style.STROKE
        isAntiAlias = true
    }
    val textPaint = Paint().apply {
        color = Color.BLACK
        style = Paint.Style.FILL_AND_STROKE
        textSize = DisplayUtil.spToPx(14f)
        isAntiAlias = true
    }

    /**
     * [Paint.setShadowLayer] 为画笔设置阴影
     *  radius: 模糊半径，越大阴影越模糊
     *  dx:阴影在横向偏移量 正值向右偏移
     *  dxy:阴影在竖向偏移量 正值向下偏移
     *  color:阴影颜色, 对图片阴影无效
     *
     * [Paint.clearShadowLayer] 清除阴影
     */
    override fun onDraw(canvas: Canvas) {
        super.onDraw(canvas)
        textPaint.setShadowLayer(1f, 10f, 10f, Color.RED)
        val text = "setShadowLayer阴影"
        canvas.drawText(text, 50f, 80f, textPaint)
        paint.style = Paint.Style.FILL_AND_STROKE
        paint.setShadowLayer(5f, 10f, 10f, Color.GRAY)
        canvas.drawCircle(50f + textPaint.measureText(text) + 100f, 60f, 50f, paint)
        paint.style = Paint.Style.STROKE
        textPaint.clearShadowLayer()
        paint.clearShadowLayer()

        var color = Color.parseColor("#1A6888B0")
        color = Color.parseColor("#33FF0000")
        paint.setShadowLayer(DisplayUtil.dpToPx(10f), 0f, DisplayUtil.dpToPx(2f), color)
        paint.color = Color.GREEN
        paint.style = Paint.Style.FILL_AND_STROKE
        canvas.drawRoundRect(650f, 2f, 950f, 150f, 20f, 20f, paint)
        paint.style = Paint.Style.STROKE
    }
}